package com.teamwings.modules.cate.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.teamwings.modules.cate.entity.FormTableCate;
import com.teamwings.modules.cate.mapper.FormTableCateMapper;
import com.teamwings.modules.cate.service.IFormTableCateService;
import com.teamwings.common.constant.CommonConstant;
import com.teamwings.modules.head.entity.FormTableHead;
import com.teamwings.modules.head.service.IFormTableHeadService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author admin
 * @since 2021-05-05
 */
@Service
public class FormTableCateServiceImpl extends ServiceImpl<FormTableCateMapper, FormTableCate> implements IFormTableCateService {

    @Autowired
    private IFormTableHeadService formTableHeadService;

    @Override
    public List<FormTableCate> getTree() {
        // 获取form_table_cate的所有数据
        List<FormTableCate> cateEntities = baseMapper.selectList(null);

        // 顶级栏目pid为0
        return cateEntities.stream().filter(cateEntity -> "0".equals(cateEntity.getPid()))
                .peek(menu -> menu.setChildren(this.getChildren(menu, cateEntities)))
                .collect(Collectors.toList());
    }

    /**
     * 递归查找所有菜单的子菜单
     */
    private List<FormTableCate> getChildren(FormTableCate entity, List<FormTableCate> all) {
        return all.stream().filter(cateEntity -> cateEntity.getPid().equals(entity.getId()))
                .peek(cateEntity -> cateEntity.setChildren(getChildren(cateEntity, all)))
                .collect(Collectors.toList());
    }

    @Override
    @Transactional
    public void saveCate(FormTableCate cate) {
        // 处理hasChild
        String pid = cate.getPid();
        // 顶级栏目pid为0
        if (StringUtils.isNotEmpty(pid) && !pid.equals("0")) {
            // 查询pid对应的cate，将其的hasChild设置为true
            FormTableCate fatherCate = getById(pid);
            fatherCate.setHasChild(CommonConstant.YesOrNo.Yes.getValue());
            updateById(fatherCate);
        }
        // 保存当前栏目
        save(cate);
    }

    @Override
    public List<FormTableCate> queryCateTreeSync(String pid) {
        LambdaQueryWrapper<FormTableCate> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isEmpty(pid)) {
            queryWrapper.and(query -> {
                query.eq(FormTableCate::getPid, "").or()
                        .eq(FormTableCate::getPid, "0").or()
                        .isNull(FormTableCate::getPid);
            });
        } else {
            queryWrapper.eq(FormTableCate::getPid, pid);
        }

        List<FormTableCate> list = list(queryWrapper);
        if (list != null && list.size() > 0) {
            for (FormTableCate treeModel : list) {
                treeModel.setKey(treeModel.getId() + "__" + System.currentTimeMillis());
            }
        }

        return list;
    }

    @Override
    public int removeByIdMain(String id) {
        FormTableCate formTableCate = baseMapper.selectById(id);

        // 判断当前栏目下是否有未删除的自定义表单数据
        LambdaQueryWrapper<FormTableHead> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FormTableHead::getTableCateId, id);
        queryWrapper.eq(FormTableHead::getDeleted, 0);
        int count = formTableHeadService.count(queryWrapper);

        // 存在子栏目的情况下不可以删除
        // if (formTableCate.getHasChild() != null
        //         && formTableCate.getHasChild() == CommonConstant.YesOrNo.No.getValue()
        //         && count == 0 || formTableCate.getHasChild() == null && count == 0) {
        // 2022-01-13
        // 由于删除了子目录时还没有调整上级判断是否存在下级的字段 "has_child"，
        // 则暂时忽略下级检测，直接删除
        if (count == 0) {
            int i = baseMapper.deleteById(id);
            return i;
        } else {
            return 0;
        }
    }

    @Override
    @Transactional
    public int removeByIdListMain(List<String> ids) {
        int sum = 0;
        for (String id : ids) {
            sum += removeByIdMain(id);
        }
        return sum;
    }

}
